package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.suffix;

import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.SuffixUtil;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator;

/*********************************************************
 * 文件名称：SuffixDeleteByPrimaryKeyElementGenerator.java
 * 系统名称：cxycloud
 * 模块名称：org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.suffix
 * 功能说明：带后缀的根据主键删除xml生成器
 * 开发人员 @author：caoxy
 * 开发时间 @date：2023/8/28 16:23
 * 修改记录：程序版本  修改日期  修改人员  修改单号  修改说明
 *********************************************************/
public class SuffixDeleteByPrimaryKeyElementGenerator extends AbstractXmlElementGenerator {

    private final boolean isSimple;

    public SuffixDeleteByPrimaryKeyElementGenerator(boolean isSimple) {
        super();
        this.isSimple = isSimple;
    }

    @Override
    public void addElements(XmlElement parentElement) {
        XmlElement answer = new XmlElement("delete"); //$NON-NLS-1$

        answer.addAttribute(new Attribute("id",
                SuffixUtil.getSuffixMethodName(introspectedTable.getDeleteByPrimaryKeyStatementId(),introspectedTable))); //$NON-NLS-1$
        String parameterClass;
        if (!isSimple && introspectedTable.getRules().generatePrimaryKeyClass()) {
            parameterClass = introspectedTable.getPrimaryKeyType();
        } else {
            parameterClass = "map";
        }
        answer.addAttribute(new Attribute("parameterType", parameterClass)); //$NON-NLS-1$

        context.getCommentGenerator().addComment(answer);

        String sb =
                "delete from " + SuffixUtil.addTableNameSuffix(introspectedTable.getFullyQualifiedTableNameAtRuntime(),introspectedTable); //$NON-NLS-1$
        answer.addElement(new TextElement(sb));

        buildPrimaryKeyWhereClause().forEach(answer::addElement);

        if (context.getPlugins().sqlMapDeleteByPrimaryKeyElementGenerated(answer,introspectedTable)
                && SuffixUtil.isEnableSuffix(introspectedTable)) {
            SuffixUtil.deleteOldElement(parentElement,answer);
            parentElement.addElement(answer);
        }
    }
}
